<template>
  <div ref="container" class="earth-container"></div>
</template>

<script>
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// import { FontLoader } from 'three/examples/jsm/loaders/FontLoader';
// import { TextGeometry } from 'three/examples/jsm/geometries/TextGeometry';

export default {
  name: 'Earth3D',
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      earth: null,
      controls: null,
      font: null, // 用于存储加载的字体
      // 原有数据...
      markers: [
        {
          position: { lat: 39.9, lng: 116.4 }, // 北京坐标
          name: "Beijing",
          color: 0xff0000
        },
        {
          position: { lat: 40.7, lng: -74.0 }, // 纽约坐标
          name: "New York",
          color: 0x00ff00
        }
      ],
      markerObjects: [] // 存储创建的标记对象
    };
  },
  mounted() {
    this.initThree();
    this.animate();
    
  },
  methods: {
    initThree() {
     
      // 1. 创建场景
      this.scene = new THREE.Scene();

      // 2. 创建相机
      this.camera = new THREE.PerspectiveCamera(
        75,
        this.$refs.container.clientWidth / this.$refs.container.clientHeight,
        0.1,
        1000
      );
      this.camera.position.z = 1.7;
      
      // 3. 创建渲染器
      this.renderer = new THREE.WebGLRenderer({ antialias: true,
        alpha: true // 启用透明背景
       });
      this.renderer.setClearColor(0x000000, 0); // 设置透明背景
      this.renderer.setSize(
        this.$refs.container.clientWidth,
        this.$refs.container.clientHeight
      );
     
      this.$refs.container.appendChild(this.renderer.domElement);
      

      // 4. 添加轨道控制
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.enableDamping = true;
      this.controls.dampingFactor = 0.05;

      // 5. 创建地球
      this.createEarth();
      this.createMarkers()
      // // 加载字体文件
      // const fontLoader = new FontLoader();
      // fontLoader.load('https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', (font) => {
      //   this.font = font; // 存储字体以便后续使用
      //   // 添加事件
      //   this.createMarkers()
      // });
      // 添加点击事件
      this.renderer.domElement.addEventListener('click', this.handleClick, false)
    },
    handleClick(event) {
      // 获取鼠标标准化坐标
      const mouse = new THREE.Vector2(
        (event.clientX / window.innerWidth) * 2 - 1,
        -(event.clientY / window.innerHeight) * 2 + 1
      )

      // 创建射线投射器
      const raycaster = new THREE.Raycaster()
      raycaster.setFromCamera(mouse, this.camera)

      // 检测与标记的交点
      const intersects = raycaster.intersectObjects(this.markerObjects)

      if (intersects.length > 0) {
        const marker = intersects[0].object.userData.info
        console.log('点击了标记:', marker.name)
        // 这里可以触发自定义事件或显示信息
        this.$emit('marker-click', marker)
      }
    },
    createEarth() {
      // 地球材质
      const textureLoader = new THREE.TextureLoader();
      const earthTexture = textureLoader.load(require("../../../../assets/images/index/largeScreen/earth_atmos_2048.jpg"));
      const bumpMap = textureLoader.load(require("../../../../assets/images/index/largeScreen/earth_normal_2048.jpg"));
      const specularMap = textureLoader.load(require("../../../../assets/images/index/largeScreen/earth_specular_2048.jpg"));

      const material = new THREE.MeshPhongMaterial({
        map: earthTexture,
        bumpMap: bumpMap,
        bumpScale: 0.03,
        color: new THREE.Color(0x1a73e8), // 添加蓝色基调
        specular: new THREE.Color(0x00a1ff), // 更亮的高光
        specularMap: specularMap,
        // specular: new THREE.Color('grey'),
        shininess: 20, // 提高光泽度
        reflectivity: 10, // 增加反射效果
        roughness: 0.2, // 减少粗糙度，增加光泽感
        metalness: 0.5, // 增加金属感
        envMapIntensity: 0.5 // 环境贴图强度
      });

      // 地球几何体
      const geometry = new THREE.SphereGeometry(1, 64, 64);
      this.earth = new THREE.Mesh(geometry, material);
      this.scene.add(this.earth);
      
      // 添加灯光
      const ambientLight = new THREE.AmbientLight(0xffffff, 1);
      this.scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      directionalLight.position.set(5, 3, 5);
      this.scene.add(directionalLight);

      const helperLight = new THREE.DirectionalLight(0x00ffff, 0.1); // 蓝绿色辅助光
      helperLight.position.set(-5, -3, -5);
      this.scene.add(helperLight);
    },
    createMarkers() {
      const textureLoader = new THREE.TextureLoader();
      const markerTexture = textureLoader.load(require('@/assets/images/index/largeScreen/position.png'));
      this.markers.forEach(marker => {
        // 将经纬度转换为三维坐标
        const phi = (90 - marker.position.lat) * (Math.PI / 180)
        const theta = (marker.position.lng + 180) * (Math.PI / 180)

        const x = -Math.sin(phi) * Math.cos(theta)
        const y = Math.cos(phi)
        const z = Math.sin(phi) * Math.sin(theta)

        // 创建标记点
        // 创建Sprite
        const spriteMaterial = new THREE.SpriteMaterial({
          map: markerTexture,
          // color: new THREE.Color(marker.color),
          transparent: true,
          opacity: 0.9,
          depthTest: false
        });

        const sprite = new THREE.Sprite(spriteMaterial);
        sprite.position.set(x * 1.02, y * 1.02, z * 1.02); // 稍微凸出地球表面
        sprite.scale.set(0.1, 0.1, 1);
        sprite.userData = {
          info: marker,
          originalScale: { x: 0.1, y: 0.1 },
          baseTexture: markerTexture,
          // hoverTexture: hoverTexture
        };
        // // 创建按钮几何体和材质
        // const buttonGeometry = new THREE.PlaneGeometry(0.5, 0.3); // 宽度为0.5，高度为0.3
        // const buttonMaterial = new THREE.MeshBasicMaterial({ color: 0x0074d9, side: THREE.DoubleSide });
        // const buttonMesh = new THREE.Mesh(buttonGeometry, buttonMaterial);
        // buttonMesh.position.set(x * 1.1, y * 1.1, z * 1.1); // 设置按钮位置
        // this.scene.add(buttonMesh)
        // // 创建3D文本
        // // 创建文本几何体和材质
        // if (this.font) {
        //   const textGeometry = new TextGeometry("返回控制台", {
        //     font: this.font,
        //     size: 0.05, // 文字大小
        //     height: 0.01, // 文字厚度
        //     curveSegments: 12,
        //     bevelEnabled: true,
        //     bevelThickness: 0.005,
        //     bevelSize: 0.005,
        //     bevelOffset: 0,
        //     bevelSegments: 5
        //   });

        //   const textMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); // 白色文字
        //   const textMesh = new THREE.Mesh(textGeometry, textMaterial);

        //   // 将文本放置在按钮的中心位置
        //   textMesh.position.set(x * 1.1, y * 1.1, z * 1.1 + 0.05); // 稍微偏移以避免遮挡按钮
        //   textMesh.rotation.x = -Math.PI / 2; // 使文本面向相机

        //   this.scene.add(textMesh);
        // } else {
        //   this.markerObjects.push(sprite);
        // }

        this.scene.add(sprite);
        this.markerObjects.push(sprite);
      })
    },
    animate() {
      requestAnimationFrame(this.animate);
      // 更新文本朝向
      this.markerObjects.forEach(item => {
        if (item.textMesh) {
          item.textMesh.lookAt(this.camera.position);
        }
      });
      this.earth.rotation.y += 0.001; // 地球自转
      this.controls.update(); // 更新轨道控制
      this.renderer.render(this.scene, this.camera);
    },
    beforeDestroy() {
      // 组件销毁时清理资源
      this.$refs.container.removeChild(this.renderer.domElement);
    }
  }
};
</script>

<style scoped>
.earth-container {
  width: 100%;
  height: 100%;
  background: transparent;
}
</style>